/*
 * @Author: xmily
 * @Date: 2020-10-25 23:07:30
 * @LastEditors: xmily
 * @LastEditTime: 2023-06-29 19:23:09
 * @FilePath: \glxxapi\routes\wechat\index.js
 * @Description: 微信端主要处理程序
 *
 * Copyright (c) 2022 by xmily/mxthink.com.cn, All Rights Reserved.
 */

const router = require("koa-router")();
//修改为全局使用
// const wechatapi = require('co-wechat-api')
const wechatconfig = require("../../cfg/wechatconfig.js");
const sitecfg = require("../../cfg/siteconfig.js");
const axios = require("axios");
const jwt = require("jsonwebtoken");
const fs = require("fs");
const crypto = require("crypto");
const wechat = require("co-wechat");
const base = require("../../models/Fjxx");
const homeinfo = require("../../models/HomeInfo/homeinfo");
const app = require("../../app.js");
const nss = require("../../models/NewStudent/newstudentsign.js");
const nsn = require("../../models/NewStudent/newstudentnotice.js");
const temper = require("../../models/NewStudent/temperature.js");
const transschoolcode = require("../../models/TransSchool/transschoolcode.js");
const mongodb = require("mongoose");
const moment = require("moment");
const config = {
  token: wechatconfig.wechatauth.token,
  appid: wechatconfig.wechatauth.appid,
  encodingAESKey: null,
};

var access_token = null;
var api = null;
// var access_token = null;
// var api = new wechatapi(
//     wechatconfig.wechatauth.appid,
//     wechatconfig.wechatauth.appsecret,
//     null,
//     function (token) {
//         access_token = token
//     }
// );

router.prefix("/wechatforsvr");

router.use(async (ctx, next) => {
  access_token = ctx.state.wechatAccessToken;
  api = ctx.state.wechatApi;
  await next();
});
//获取素材
router.get("/getnews", async (ctx, next) => {
  try {
    let result = await api.getMaterials("news", 0, 20);
    console.log(JSON.stringify(result));
    ctx.body = JSON.stringify(result);
  } catch (err) {
    ctx.body = err.message;
  }
});
//接口配置信息
router.get("/config", async (ctx, next) => {
  let signature = ctx.query.signature;
  let echostr = ctx.query.echostr;
  let timestamp = ctx.query.timestamp;
  let nonce = ctx.query.nonce;
  ctx.body = echostr; //signature+"|"+echostr+"|"+timestamp+"|"+nonce;
});
router.post("/config", async (ctx, next) => {
  ctx.body = "eafadf";
});
const templateMsg = {
  // id: "k0LQ35MaRiRiQXif4EynZU609CAOEkeCqHU_CD3dpbk",
  id: "3wyDQ1M-pZwMZRAImEZYE2LW-AljrHgh9M9LB2TOQnA",
  url: "",
  data: {
    first: {
      value:
        "\040\040\040\040\040\040\040\040XXX小孩的家长您好，为方便领取入学通知书，学校采取错峰领取通知书的方式进行发放，特通知如下：",
      color: "",
    },
    keyword1: {
      value: "桂林市桂岭小学",
      color: "",
    },
    keyword2: {
      value: "学校教导处",
      color: "",
    },
    keyword3: {
      value: "2020年8月20日",
      color: "",
    },
    keyword4: {
      value:
        "\r\040\040\040\040\040\040\040\040请家长于8月20日 上午9：00到学校领取入学通知书（领取时请出示该条通知，及学生的户口本，并翻至小孩所在那一页）。",
      color: "",
    },
    remark: {
      value:
        "学生姓名：XXX，\r报名序号：XXX，\r面审序号：XXX\r领取时请告知面审序号",
      color: "",
    },
  },
};
//发送“学校通知”模板消息
async function sendtemplateMsg() {
  // let wxuser = await nsn.findByQuery({_id:{$gt:"6118e4b1fa1e0c3ddc006f0c"}})
  let wxuser = await nsn.findByQuery({ readed: null });
  for (let o in wxuser) {
    templateMsg.id = "nkB7dzU1SPilVScbprmuYyVMU4gKwm5v3n44VogCsUQ";
    // templateMsg.id="qt0f5N9ujzlBN8SPWHKPsd9eD2-SELwJClOgpVXSAEA";
    templateMsg.url =
      // "https://wechat.frp.mxthink.com.cn/xmng/notice?wxopenid=" +
      sitecfg.isbindertoURL+"notice?wxopenid="+
      wxuser[o].openid;
    templateMsg.data.first.value =
      "\040\040\040\040\040\040\040\040" +
      wxuser[o].学生姓名 +
      "的家长您好，因疫情防控要求，学校采取错峰领取通知书的方式进行发放，特通知如下：";
    templateMsg.data.keyword1.value = wxuser[o].学生姓名;
    templateMsg.data.keyword2.value = wxuser[o].fid//"领取时间:" + wxuser[o].time;
    templateMsg.data.keyword3.value=wxuser[o].报名序号
    templateMsg.data.keyword4.value=wxuser[o].time;
      templateMsg.data.remark.value =
        "\r\040\040\040\040\040\040\040\040领取时请出示该条通知或者出示学生的户口本，并翻至小孩所在那一页。\r\040\040\040\040\040\040\040\040请家长及时加入新生QQ群，QQ群号：587101771\r报名序号：" +
        wxuser[o].报名序号 +
        "，\r面审序号：" +
        wxuser[o].fid +
        "\r领取时请告知面审序号\r点击该通知确认收到";
    
    //  else {
    //   templateMsg.data.remark.value =
    //     "\r\040\040\040\040\040\040\040\040领取时请出示该条通知或者出示学生的户口本，并翻至小孩所在那一页。" +
    //     wxuser[o].报名序号 +
    //     "，\r面审序号：" +
    //     wxuser[o].fid +
    //     "\r领取时请告知面审序号\r点击该通知确认收到";
    // }
    if (
      "钟嘉懿".indexOf(
        wxuser[o].学生姓名
      ) != -1
    ){
      console.log(wxuser[o].学生姓名+"不发送")
    }else{
    console.log(wxuser[o].学生姓名);
    try {
      let res = await api.sendTemplate(
        wxuser[o].openid,
        templateMsg.id,
        templateMsg.url,
        "#173177",
        templateMsg.data
      );

      console.log("完成发送：" + res.msgid);
      await nsn.updateone(
        { openid: wxuser[o].openid },
        { $set: { msgid: res.msgid } }
      );
    } catch (err) {
      await nsn.updateone(
        { openid: wxuser[o].openid },
        { $set: { msgid: err.message } }
      );
      console.log(err.message);
    }
  }
  }
  // console.log(wxuser);
}
router.get("/sendtemplatemsg", async (ctx, next) => {
  await sendtemplateMsg();

  ctx.body = "完成发送";
});
//发送疫情未打卡模板消息
router.get("/dakamsg", async (ctx, next) => {
  let list = [
    "婧婧",
    "何义龙",
  ];
  // let list=["婧婧","徐李"]
  let date1 = "29日";
  let output = "";
  let stulist = await nsn.findByQuery({ 学生姓名: { $in: list } });
  templateMsg.id = "2BL2RPlibxwVhb3RY64UjifX1ukvYeiM1g9uXs6Dwts";
  templateMsg.url = "https://docs.qq.com/form/page/DQnp5RnF4ck5HamtD";

  for (let o in stulist) {
    templateMsg.data.first.value =
      stulist[o].学生姓名 +
      "的家长您好，小孩" +
      date1 +
      "的健康打卡还未完成，请点击该条消息完成打卡，感谢您对学校疫情防控工作的支持。";
    templateMsg.data.keyword1.value = stulist[o].学生姓名;
    templateMsg.data.keyword2.value = "未完成的日期：" + date1;
    templateMsg.data.keyword3.value = "尚未完成学生健康打卡";
    templateMsg.data.keyword4.value = "桂林市桂岭小学";
    templateMsg.data.remark.value =
      "请点击该条消息打卡，或者移步到学校一年级新生QQ群中点击相应链接完成打卡。填写时日期注意选择" +
      date1 +
      "。";
    console.log(stulist[o].学生姓名);
    try {
      // let res = await api.sendTemplate(stulist[o].openid, templateMsg.id, templateMsg.url, "#173177", templateMsg.data)
      console.log(stulist[o].学生姓名 + "完成发送：" + res.msgid);
      output += stulist[o].学生姓名 + "完成发送：" + res.msgid + "\n\r";
    } catch (err) {
      console.log(err.message);
      output += err.message + "\n\r";
    }
  }
  ctx.body = output;
});

async function sendMsg(openidlist, msg) {
  for (let o in openidlist) {
    templateMsg.data.first.value = "学校提醒";
    templateMsg.data.keyword3.value = "2020年8月22日";
    templateMsg.data.keyword4.value =
      "\040\040\040\040\040\040\040\040" +
      "家长您好，收到该条消息说明您尚未按入学通知书上的要求添加“桂林市凤集小学2020级新生”QQ群，请收到该条消息后及时添加，以免遗漏学校重要通知和消息。QQ群号为：775286239 或者扫描入学通知上的二维码。";
    templateMsg.data.remark.value = "";
    try {
      let res = await api.sendTemplate(
        openidlist[o],
        templateMsg.id,
        "",
        "#173177",
        templateMsg.data
      );
      console.log("完成发送：" + res.msgid);
    } catch (err) {
      console.log(err.message);
    }
  }
}
async function validityLocalUserIsBinder(openid) {
  let wxuserinfo = {
    openid: openid,
    isbinder: false,
    error: false,
  };
  try {
    let finduser = await nss.findbyquery({ wxopenid: openid });
    if (finduser.length == 1) {
      wxuserinfo.isbinder = true;
      let token = jwt.sign(wxuserinfo, sitecfg.tokenKey, { expiresIn: "1h" });
      return token;
    } else {
      return null;
    }
  } catch (err) {
    //根据openid 查询数据库时出错，这里后期要放置出错界面
    wxuserinfo.error = true;
    console.log(err);
    ctx.body = err;
    return;
  }
}
router.get("/作废", async (ctx, next) => {
  if (!ctx.query.code) {
    //如果没有获得code表示来源客户端不是微信
    ctx.body = errhtml;
    return;
  }

  if (ctx.request.token) {
    //如果已经访问者已经获得token
    ctx.redirect(sitecfg.clientURL + "/?token=" + ctx.request.authorization);
    return;
  }
  //let code=ctx.query.code;

  //访问者没有token只有code，通过 code获得token
  let wxuserinfo = {
    code: ctx.query.code,
    openid: null,
    isbinder: false,
    error: false,
  };

  let getopenidurl =
    "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" +
    wechatconfig.wechatauth.appid +
    "&secret=" +
    wechatconfig.wechatauth.appsecret +
    "&code=" +
    wxuserinfo.code +
    "&grant_type=authorization_code";

  try {
    let result = await axios.get(getopenidurl);
    if (result.data.errcode) {
      ctx.body = result.data.errmsg;
      return;
    } else {
      wxuserinfo.openid = result.data.openid;
    }
  } catch (err) {
    //获取用户授权出错了，跳转到出错页面
    console.log("获取用户授权出错:" + err);
    wxuserinfo.error = true;
    ctx.body = err;
    return;
  }

  //判断是否已与本地用户库绑定

  try {
    if (!wxuserinfo.isbinder) {
      let finduser = await nss.findbyquery({ wxopenid: wxuserinfo.openid });
      if (finduser.length == 1) wxuserinfo.isbinder = true;
      let token = jwt.sign(wxuserinfo, sitecfg.tokenKey, { expiresIn: "1h" });
      ctx.redirect(sitecfg.clientURL + "?token=" + token);
      //ctx.redirect("http://mxthink.cross.echosite.cn/vwechatenter2020/" + "?token=" + token)
      // ctx.redirect(sitecfg.serverURL + "/?token=" + token)
    }
  } catch (err) {
    //根据openid 查询数据库时出错，这里后期要放置出错界面
    wxuserinfo.error = true;
    console.log(err);
    ctx.body = err;
    return;
  }
  ctx.body = wxuserinfo.openid;
});
//在校生微信与学生绑定
//
/**
 * @description: 微信学生用户入口
 * @param {*}
 * @return {*}
 */
router.get("/", async (ctx, next) => {
  // let signature = ctx.query.signature;
  // let echostr = ctx.query.echostr;
  // let timestamp = ctx.query.timestamp;
  // let nonce = ctx.query.nonce;
  // ctx.body = echostr;
  // return
  let code = ctx.query.code;

  //使用token认证，以上代码改为以下代码：
  if (!ctx.query.code) {
    //如果没有获得code表示来源客户端不是微信
    ctx.body = errhtml;
    return;
  }

  // if (ctx.request.token) {
  //     //访问者已经获得token
  //     ctx.redirect(sitecfg.clientURL + "/?token=" + ctx.request.authorization)
  //     return;
  // }

  let wxuserinfo = {
    code: ctx.query.code,
    openid: null,
    isbinder: false,
    error: false,
    role: null,
    accountname: "",
    gender: "女",
    classno: "",
    grade: "",
    userid: "",
  };
  //访问者没有token只有code，通过 code获得token
  let getopenidurl =
    "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" +
    wechatconfig.wechatauth.appid +
    "&secret=" +
    wechatconfig.wechatauth.appsecret +
    "&code=" +
    wxuserinfo.code +
    "&grant_type=authorization_code";

  try {
    let result = await axios.get(getopenidurl);
    if (result.data.errcode) {
      ctx.body = result.data.errmsg;
      return;
    } else {
      wxuserinfo.openid = result.data.openid;
    }
  } catch (err) {
    //获取用户授权出错了，跳转到出错页面
    console.log("获取用户授权出错:" + err);
    wxuserinfo.error = true;
    ctx.body = err;
    return;
  }

  try {
    // if (!wxuserinfo.isbinder) {
    //let finduser = await nss.findbyquery({ 'wxopenid': wxuserinfo.openid })
    // let finduser = await base.myFindByQuery({ 'wxopenid': wxuserinfo.openid })
    let finduser = await base.myAggregate([
      {
        $match: {
          wxopenid: wxuserinfo.openid,
          // $or:[{accountType: "学生"},{accountType: "毕业生"},{}]
          accountType: { $in: ["学生", "毕业生", "新生"] },
        },
      },
      {
        $lookup: {
          from: "baseExtendInfo",
          localField: "_id",
          foreignField: "baseid",
          as: "baseExtendInfo",
        },
      },
      {
        $unwind: {
          path: "$baseExtendInfo",
          preserveNullAndEmptyArrays: true,
        },
      },
      {
        $project: {
          _id: 1,
          username: 1,
          gender: 1,
          wxopenid: 1,
          role: 1,
          accountType: 1,
          grade: 1,
          "baseExtendInfo.班级": 1,
          "baseExtendInfo.学籍号": 1,
        },
      },
    ]);

    if (finduser.length == 1) {
      wxuserinfo.isbinder = true;
      wxuserinfo.role = finduser[0].role;
      wxuserinfo.accountType = finduser[0].accountType;
      wxuserinfo.accountname = finduser[0].username;
      wxuserinfo.grade = finduser[0].grade;
      wxuserinfo.classno =
        finduser[0].accountType != "学生" && finduser[0].accountType != "毕业生"
          ? "非学生用户"
          : finduser[0].baseExtendInfo.班级;
      wxuserinfo.sid = finduser[0].baseExtendInfo.学籍号;
      wxuserinfo.userid = finduser[0]._id;
      wxuserinfo.gender = finduser[0].gender;
    }
    let token = jwt.sign(wxuserinfo, sitecfg.tokenKey, { expiresIn: "1h" });

    if (wxuserinfo.isbinder) {
      // ctx.redirect("http://121.31.126.175:6061/"+"?token="+token)
      ctx.redirect(sitecfg.isbindertoURL + "?token=" + token);
    } else {
      ctx.redirect(sitecfg.clientURL + "login?token=" + token);
    }
    // }
  } catch (err) {
    //根据openid 查询数据库时出错，这里后期要放置出错界面
    wxuserinfo.error = true;
    console.log(err);
    ctx.body = err;
    return;
  }
});

/**
 * @description: 微信教师用户入口
 * @param {*}
 * @return {*}
 */
router.get("/t", async (ctx, next) => {
  //使用token认证，以上代码改为以下代码：
  if (!ctx.query.code) {
    //如果没有获得code表示来源客户端不是微信
    ctx.body = errhtml;
    return;
  }

  let wxuserinfo = {
    code: ctx.query.code,
    openid: null,
    isbinder: false,
    error: false,
    role: null,
    accountname: "",
    gender: "女",
    classno: "",
    userid: "",
  };
  //访问者没有token只有code，通过 code获得token
  let getopenidurl =
    "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" +
    wechatconfig.wechatauth.appid +
    "&secret=" +
    wechatconfig.wechatauth.appsecret +
    "&code=" +
    wxuserinfo.code +
    "&grant_type=authorization_code";

  try {
    let result = await axios.get(getopenidurl);
    if (result.data.errcode) {
      ctx.body = result.data.errmsg;
      return;
    } else {
      wxuserinfo.openid = result.data.openid;
    }
  } catch (err) {
    //获取用户授权出错了，跳转到出错页面
    console.log("获取用户授权出错:" + err);
    wxuserinfo.error = true;
    ctx.body = err;
    return;
  }

  try {
    if (!wxuserinfo.isbinder) {
      let finduser = await base.myFindOne(
        {
          $and: [
            {
              wxopenid: wxuserinfo.openid,
            },
            {
              accountType: {
                $in: ["教师", "管理员"],
              },
            },
          ],
        },
        {
          _id: 1,
          username: 1,
          gender: 1,
          wxopenid: 1,
          role: 1,
          accountType: 1,
          grade: 1,
          classno: 1,
        }
      );

      if (finduser) {
        wxuserinfo.isbinder = true;
        wxuserinfo.role = finduser.role;
        wxuserinfo.accountType = finduser.accountType;
        wxuserinfo.accountname = finduser.username;
        wxuserinfo.classno = finduser.classno;
        wxuserinfo.grade = finduser.grade;
        // wxuserinfo.sid = finduser[0].baseExtendInfo.学籍号;
        wxuserinfo.userid = finduser._id;
        wxuserinfo.gender = finduser.gender;
      }
      let token = jwt.sign(wxuserinfo, sitecfg.tokenKey, { expiresIn: "1h" });

      if (wxuserinfo.isbinder) {
        // ctx.redirect("http://121.31.126.175:6061/"+"?token="+token)
        ctx.redirect(sitecfg.isbindertoURL + "?token=" + token);
        // ctx.redirect("http://school.mxthink.com.cn:8800/glwechat/?toekn="+token)
      } else {
        ctx.redirect(
          sitecfg.clientURL +
            "login4?token=" +
            token +
            "&openid=" +
            wxuserinfo.openid
        );
        // ctx.redirect("http://school.mxthink.com.cn:8800/wechat/login3?token="+token)
      }
    }
  } catch (err) {
    //根据openid 查询数据库时出错，这里后期要放置出错界面
    wxuserinfo.error = true;
    console.log(err);
    ctx.body = err;
    return;
  }
});

//新生入学面审序号绑定
router.get("/newstu/", async (ctx, next) => {
  //正式开始获取面审序号时注释掉以下内容
  // ctx.type="text/html;charset=utf-8"
  // ctx.body="<html><head><title>桂林市桂岭小学</title></head><body><h1>暂时未开通，待网上报名结束后，收到短信后再操作。</h1></body></html>"
  // return;
  //正式开始获取面审序号时注释掉以上内容

  // ctx.redirect("http://mxthink.frp.luckylxh.top/xmng/unsign")
  // return
  let code = ctx.query.code;

  //使用token认证，以上代码改为以下代码：
  if (!ctx.query.code) {
    //如果没有获得code表示来源客户端不是微信
    ctx.body = errhtml;
    return;
  }

  // if (ctx.request.token) {
  //     //访问者已经获得token
  //     ctx.redirect(sitecfg.clientURL + "/?token=" + ctx.request.authorization)
  //     return;
  // }

  let wxuserinfo = {
    code: ctx.query.code,
    openid: null,
    isbinder: false,
    error: false,
  };
  //访问者没有token只有code，通过 code获得token
  let getopenidurl =
    "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" +
    wechatconfig.wechatauth.appid +
    "&secret=" +
    wechatconfig.wechatauth.appsecret +
    "&code=" +
    wxuserinfo.code +
    "&grant_type=authorization_code";

  try {
    let result = await axios.get(getopenidurl);
    if (result.data.errcode) {
      ctx.body = result.data.errmsg;
      return;
    } else {
      wxuserinfo.openid = result.data.openid;
    }
  } catch (err) {
    //获取用户授权出错了，跳转到出错页面
    console.log("获取用户授权出错:" + err);
    wxuserinfo.error = true;
    ctx.body = err;
    return;
  }

  try {
    if (!wxuserinfo.isbinder) {
      let finduser = await nss.findbyquery({ wxopenid: wxuserinfo.openid });
      if (finduser.length == 1) wxuserinfo.isbinder = true;
      let token = jwt.sign(wxuserinfo, sitecfg.tokenKey, { expiresIn: "1h" });
      if (wxuserinfo.isbinder) {
        // ctx.redirect("http://121.31.126.175:6061/"+"?token="+token)
        //关于面审序号获取
        ctx.redirect(
          //开放面审序号获取
          sitecfg.isbindertoURL + "newstudent?token=" + token
        );
      } else {
        //开放时注释以下语句
        //ctx.redirect(sitecfg.isbindertoURL + "notopen?token=" + token);
        //开放时取下以下注释
        ctx.redirect(sitecfg.clientURL + "login2?token=" + token);
      }
    }
  } catch (err) {
    //根据openid 查询数据库时出错，这里后期要放置出错界面
    wxuserinfo.error = true;
    console.log(err);
    ctx.body = err;
    return;
  }
});

//处理微信端消息的总入口
router.post(
  "/",
  wechat(config).middleware(async (message, ctx) => {
    console.log(message);
    let key1 = /招生|2023招生|新生入学|入学|指南|招生指南|报名/gi;
    let key2 = /接种|儿童预防接种证自助查询方法/gi;
    if (message.MsgType === "text") {
      if (key1.test(message.Content)) {
        //招生简章文章获取
        return [
          {
            title: "桂林市桂岭小学2023年秋季学期一年级新生招生简章",
            description: "",
            picurl:
              "http://mmbiz.qpic.cn/mmbiz_jpg/XXZD96wvpMDeuZvsSNrHuY5tWib9OGsuW3js7YGgc0ibc9Zxb2RzCd8EwT3qUtKdA869bP9GwS7gKibvu5ySQkRQg/0?wx_fmt=jpeg",
            url: "https://mp.weixin.qq.com/s?__biz=MzIwMzIwMTgwNg==&mid=2653683334&idx=1&sn=caf1901114e3a80130721a63209d23c4&chksm=8d0c52e7ba7bdbf1660efded94dd13bd0dd73eb717764604ea54369862d442f59f970fadee91#rd",
          },
        ];
        // api.sendMpNews(message.FromUserName, 'TBoatSltT2nX5RMcq5L3Xo49V31s_GCi1Se4yC6c0eU')
        // return '';//"命中" + message.Content
        //return "<xml><ToUserName>"+message.FromUserName+"</ToUserName><FromUserName>"+message.ToUserName+"</FromUserName><CreateTime>12345678</CreateTime><MsgType>text</MsgType><Content><![CDATA[你好]]></Content></xml>"
      } else if (key2.test(message.Content)) {
        //自助查验接种文章获取获取
        return [
          {
            title: "儿童预防接种证自助查验方法",
            description: "",
            picurl:
              "http://mmbiz.qpic.cn/mmbiz_jpg/XXZD96wvpMCejnXB4Ad7yG7jg7NiaicWrfkXTZT3PN34hoqUvjMV4Q1rRScldZX7ao7EmHZ8zEO6GED5aNl0FWMA/0?wx_fmt=jpeg",
            url: "http://mp.weixin.qq.com/s?__biz=MzIwMzIwMTgwNg==&mid=506192957&idx=6&sn=6e5eaa81d1395a06a95fdd9f80613bdf&chksm=0d0c485c3a7bc14a0ec0206ad98f72f955153db5b5bba47dc5a48ed35a1fc526c6b1dc7903d0#rd",
          },
        ];
      } else if (message.Content === "模板消息") {
        //测试用
        templateMsg.url = "https://wechat.frp.mxthink.com.cn/xmng/transschool";
        templateMsg.id = "fIpKUkjumehiVsOXKIGW5DZ38lW1mu21jNSzvCS4Drk";
        templateMsg.data.first.value = "请点击该消息完成转学信息填报";
        templateMsg.data.keyword1.value = "测试";
        templateMsg.data.keyword2.value = "2012年2月2日前完成";
        templateMsg.data.remark.value =
          "填写时请将户口本和住地证明（房产证等）拿在身边，";

        api.sendTemplate(
          "oDvvsvqzDHUHwV49tRvK7czoCDvQ",
          templateMsg.id,
          templateMsg.url,
          "#173177",
          templateMsg.data
        );
        //sendtemplateMsg();
        //let openidlist = ['opFC7v6PGMPcKy6w2iJkdykPEuWE', 'opFC7v4XMuF4S8P0U5i2n8NX3GCI', 'opFC7vxfNH3gtI1Z0x-FpyEyrLFI', 'opFC7vwWZos9RBB8ARfHjErjjRrI', 'opFC7v3H26aJ8AwOVF9IOwb_1Psk', 'opFC7v5Pl9lJeFws35DcKJpJw2ts', 'opFC7vzDCA_z8J19ZOSRhABi5PtA', 'opFC7v_UIvb5faVJX7eX42m_5JtM', 'opFC7vzgBbsDS4PL2KtBBOZtgWDo', 'opFC7v2kPaF_Dc2__6EiKGpGPYyg']
        //sendMsg(openidlist, "收到该条消息说明您尚未按入学通知书上的要求添加“桂林市凤集小学2020级新生”QQ群，请收到该条消息后及时添加。QQ群号为：775286239 或者扫描入学通知上的二维码。")
        return "";
      } else if (
        /转学码：/gi.test(message.Content) &&
        message.FromUserName === "oDvvsvqzDHUHwV49tRvK7czoCDvQ"
      ) {
        //转学码模板消息反馈
        // let stuname=/转学码：(.*)/gi.match(message.Content)
        let stuname = /(转学码：){1}(.*)/gm.exec(message.Content);
        console.log(stuname);
        if (stuname[2] != "") {
          let time = new Date();
          let tempcode = Math.floor(Math.random() * 4999) + 5000;
          await transschoolcode.Save({
            name: stuname[2],
            expireAt: time.setTime(time.getTime() + 3600 * 1000 * 12),
            value: tempcode,
          });
          return (
            stuname[2] +
            "的转学码：【 " +
            tempcode +
            " 】 （请在12小时内完成信息填写。）"
          );
        } else {
          return "错误：未匹配到姓名";
        }
      } else if (/^\d{4}$/.test(message.Content)) {
        //家长获取转学链接消息模板反馈
        let findcode = await transschoolcode.getByQuery({
          value: message.Content,
        });
        if (findcode) {
          templateMsg.url =
            "https://wechat.frp.mxthink.com.cn/glwechat/transschool?code=" +
            findcode.value;
          templateMsg.id = "fIpKUkjumehiVsOXKIGW5DZ38lW1mu21jNSzvCS4Drk";
          templateMsg.data.first.value = "请点击该消息完成转学信息填报";
          templateMsg.data.keyword1.value = findcode.name;
          templateMsg.data.keyword2.value =
            "请于" +
            moment(findcode.expireAt).utcOffset(8).format("YYYY/MM/DD HH:mm") +
            "前完成信息填写";
          templateMsg.data.remark.value =
            "填写时请将户口本和住地证明（房产证等）拿在身边，户籍地址及家庭地址请按证件上的内容填写；请在规定时间内完成，过期将无法录入。";

          api.sendTemplate(
            message.FromUserName,
            templateMsg.id,
            templateMsg.url,
            "#173177",
            templateMsg.data
          );
          return "";
        } else {
          return "该公众号暂不支持在线消息回复功能。了解2022秋季招生信息请回复“招生”。"; //，了解2020网上报名流程请回复“网上报名”"
        }
      } else {
        /*
        else if(/(姓名[：|:]){1}(.*)/gm.exec(message.Content)){                                                   //学校间调剂后消息模板反馈
            let stuname=/(姓名[：|:]){1}(.*)/gm.exec(message.Content)
            let stuinfo=await nsn.findOneByQuery({学生姓名:stuname[2]})

            if(stuname[2]!=""&&stuinfo){
                await nsn.updateone({ 学生姓名:stuname[2] }, { $set: { "openid": message.FromUserName } })
                templateMsg.id = "nkB7dzU1SPilVScbprmuYyVMU4gKwm5v3n44VogCsUQ"
                templateMsg.url = "https://wechat.frp.mxthink.com.cn/xmng/notice?wxopenid=" + message.FromUserName
                templateMsg.data.first.value = '\040\040\040\040\040\040\040\040' + stuname[2] + '的家长您好，因疫情防控要求，学校采取错峰领取通知书的方式进行发放，特通知如下：';
                templateMsg.data.keyword1.value = stuname[2]
                templateMsg.data.keyword2.value = stuinfo.fid+" (小孩不用来，仅用于查找)";
                templateMsg.data.keyword3.value = stuinfo.报名序号;
                templateMsg.data.keyword4.value = stuinfo.time;
                templateMsg.data.remark.value = "\r\040\040\040\040\040\040\040\040领取时请出示该条通知及叠彩区教育局的调剂通知书。\r请家长及时加入新生QQ群，QQ群号：965878103\r报名序号：" + stuinfo.报名序号 + "，\r面审序号：" + stuinfo.fid + "\r领取时请告知面审序号\r点击该通知确认收到"
                try {
                    let res = await api.sendTemplate(message.FromUserName, templateMsg.id, templateMsg.url, "#173177", templateMsg.data);
                    console.log("完成发送：" + res.msgid)
                    await nsn.updateone({ openid: message.FromUserName }, { $set: { "msgid": res.msgid } })
                } catch (err) {
                    await nsn.updateone({ openid: message.FromUserName }, { $set: { "msgid": err.message } })
                    console.log(err.message)
                }
                let countstu = await nsn.countByQuery({ $and: [{ _id: { $gt: "61192d91fa1e0c3ddc006f17" } }, { openid: { $ne: null } }] });
                await api.sendText('oDvvsvqzDHUHwV49tRvK7czoCDvQ', "学生姓名："+stuname[2]+" 第【"+countstu+"】个");

                return ""
            } else {
                return "错误：未匹配到姓名，请检查姓名是否输入正确。"
            }

            console.log(message.FromUserName+"命中调剂")
        }
        */
        /*
        else if(/^([^\x00-\xff]{3,4})(\d{11})$/gm.exec(message.Content)){                 //局调生通知模板发送部分
            let stuinfo=/^([^\x00-\xff]{3,4})(\d{11})$/gm.exec(message.Content)
            let stuname=stuinfo[1]
            let stutel=stuinfo[2]
            let stuindata=await nsn.findOneByQuery({学生姓名:stuname,fid:stutel})
            if(stuindata){
                await nsn.updateone({ 学生姓名:stuname}, { $set: { "openid": message.FromUserName } })
                templateMsg.id = "VgaocNWnkbQpA-g-2HvBadOwUFxqgLqYNOCcCNN17iA"
                templateMsg.url = ""
                templateMsg.data.first.value = '\040\040\040\040\040\040\040\040' + stuname + '的家长您好，您的孩子现分配到我校就读，请按以下时间到校审核材料。';
                templateMsg.data.keyword1.value = stuname
                templateMsg.data.keyword2.value = stuindata.time
                templateMsg.data.remark.value = "\r\040\040\040\040\040\040\040\040请家长携带小孩及监护人的户口本，居住证明材料（房产证或者是租房合同等）到校审核登记。"
                try {
                    let res = await api.sendTemplate(message.FromUserName, templateMsg.id, templateMsg.url, "#173177", templateMsg.data);
                    console.log("完成发送：" + res.msgid)
                    await nsn.updateone({ openid: message.FromUserName }, { $set: { "msgid": res.msgid } })
                } catch (err) {
                    await nsn.updateone({ openid: message.FromUserName }, { $set: { "msgid": err.message } })
                    console.log(err.message)
                }
                //let countstu = await nsn.countByQuery({ $and: [{ _id: { $gt: "61192d91fa1e0c3ddc006f17" } }, { openid: { $ne: null } }] });
                await api.sendText('oDvvsvqzDHUHwV49tRvK7czoCDvQ', "(局)学生姓名："+stuname);

                return ""
            }else{
                return "无法查询到该学生，请检查学生姓名和手机号是否正确、输入格式是否正确。"
            }
            // return stuname+"|"+stutel
        }
        */
        /*
        else if(message.Content==="体温"){
            let temperString=""
            try{
                let stuindata=await nsn.findOneByQuery({openid:message.FromUserName})
                // let stuindata=await nsn.findOneByQuery({openid:"oDvvsvsFkEmENopzaeupqm9ZTc9M"})
                if(stuindata){
                    let temperlist=await temper.getTemperByName(stuindata.学生姓名)

                    for(let o in temperlist){
                        temperString+=temperlist[o].stuname+temperlist[o].date+"日,体温为："+temperlist[o].temperature+"\r"
                    }
                    return temperString;
                }else{
                    return "当前微信用户无法查找到对应的学生信息。"
                }
            }catch(err){
                console.log(err)
                return "查询出错"
            }
        } */
        return "该公众号暂不支持在线消息回复功能。了解2022秋季招生信息请回复“招生”。了解儿童预防接种证自助查验方法请回复“接种”";
      }
      // return message.Content
    } else if (message.MsgType === "event") {
      if (message.Event === "subscribe") {
        return "感谢订阅";
      } else if (message.Event === "TEMPLATESENDJOBFINISH") {
        if (message.Status === "success") {
          console.log("收到模板消息,消息ID：" + message.MsgID);
          await nsn.updateone(
            { msgid: message.MsgID },
            { $set: { sendresult: "收到" } }
          );
        } else {
          console.log("拒收模板消息" + message.MsgID);
          await nsn.updateone(
            { msgid: message.MsgID },
            { $set: { sendresult: "拒收" } }
          );
        }
      } else if (message.Event === "VIEW") {
        if (await validityLocalUserIsBinder(message.FromUserName)) {
          console.log("is binder");
        } else {
          ctx.body = "<script>window.location.href='www.163.com'</script>";
        }
      }
    } else {
      return "该公众号目前不支持非文本消息的处理功能。";
    }
    // if(message.Content="登记表"){
    //     return {
    //         type: "image",
    //         content: {
    //           mediaId: 'mediaId'
    //         }
    //       };
    // }
  })
);

// router.post("/",wechat(config,(req,res,next)=>{

// }))

//菜单配置
var mymenu3 = {
  button: [
    {
      name: "蕴雅教育",
      type: "view",
      url: "https://mp.weixin.qq.com/mp/homepage?__biz=MzIwMzIwMTgwNg==&hid=1&sn=2a21226308c7f7f837358fb19ac88580",
    },
    {
      name: "新生相关",
      sub_button: [
        {
          type: "article_id",
          name: "招生相关资料",
          article_id:
            "Vs2LoFNiSSgmhV7z1fdpi6pM5REMoUg54JrBzjA4Jxls0hTuw-ckCXc8DYGxF6_E",
        },
        {
          type: "view",
          name: "获取面审序号",
          url:
            "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
            wechatconfig.wechatauth.appid +
            "&redirect_uri=" +
            encodeURIComponent(sitecfg.wechatLoginJumpUrl + "/newstu") +
            "&response_type=code&scope=snsapi_base&state=123#wechat_redirect",
        },
      ],
    },
    {
      name: "个人中心",
      sub_button: [
        {
          name: "金桂学子",
          type: "view",
          url:
            "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
            wechatconfig.wechatauth.appid +
            "&redirect_uri=" +
            encodeURIComponent(
              // "https://wechat.frp.mxthink.com.cn/api/wechatforsvr"
              sitecfg.wechatLoginJumpUrl
            ) +
            "&response_type=code&scope=snsapi_base&state=123#wechat_redirect",
        },
        {
          name: "儒雅教师",
          type: "view",
          url:
            "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
            wechatconfig.wechatauth.appid +
            "&redirect_uri=" +
            encodeURIComponent(
              // "https://wechat.frp.mxthink.com.cn/api/wechatforsvr/t"
              sitecfg.wechatLoginJumpUrl + "/t"
            ) +
            "&response_type=code&scope=snsapi_base&state=123#wechat_redirect",
        },
      ],
    },
  ],
};
var mymenu2 = {
  button: [
    {
      name: "蕴雅教育",
      type: "view",
      url: "https://mp.weixin.qq.com/mp/homepage?__biz=MzIwMzIwMTgwNg==&hid=1&sn=2a21226308c7f7f837358fb19ac88580",
    },
    {
      name: "秋季招生",
      sub_button: [
        {
          type: "view",
          name: "获取面审序号",
          url:
            "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
            wechatconfig.wechatauth.appid +
            "&redirect_uri=" +
            encodeURIComponent(
              "https://wechat.frp.mxthink.com.cn/api/wechatforsvr/newstu"
            ) +
            "&response_type=code&scope=snsapi_base&state=123#wechat_redirect",
        },
        // {
        //     "type": "media_id",
        //     "name":"招生相关资料",
        //     "media_id": "TBoatSltT2nX5RMcq5L3Xo49V31s_GCi1Se4yC6c0eU"
        // }
      ],
    },
    {
      name: "金桂学子",
      type: "view",
      url:
        "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
        wechatconfig.wechatauth.appid +
        "&redirect_uri=" +
        encodeURIComponent(
          "https://wechat.frp.mxthink.com.cn/api/wechatforsvr"
        ) +
        "&response_type=code&scope=snsapi_base&state=123#wechat_redirect",
    },
  ],
};
var mymenu = {
  button: [
    {
      name: "新生入学",
      sub_button: [
        {
          type: "view",
          name: "获取面审序号",
          url:
            "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
            wechatconfig.wechatauth.appid +
            "&redirect_uri=" +
            encodeURIComponent(
              "https://wechat.frp.mxthink.com.cn/wechatforsvr/newstu"
            ) +
            "&response_type=code&scope=snsapi_base&state=123#wechat_redirect",
        },
        {
          type: "click",
          name: "2021招生简章",
          key: "V1001_GOOD",
        },
      ],
    },
    // {
    //     "name": "和美凤集",
    //     "type": "view",
    //     "url": 'https://mp.weixin.qq.com/mp/homepage?__biz=MzIxNjcyNDEzMg==&hid=1&sn=c7ad585fa9ceeb4aea3fae241481ffb7'
    // },
    {
      name: "金桂学子",
      type: "view",
      url:
        "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
        wechatconfig.wechatauth.appid +
        "&redirect_uri=" +
        encodeURIComponent(
          "https://wechat.frp.mxthink.com.cn/api/wechatforsvr"
        ) +
        "&response_type=code&scope=snsapi_base&state=123#wechat_redirect",
    },

    // {
    //     "name": "测试",
    //     "type": "view",
    //     "url": 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + wechatconfig.wechatauth.appid + '&redirect_uri=' + encodeURIComponent("http://mxthink.cross.echosite.cn/vwechatenter2020/") + '&response_type=code&scope=snsapi_base&state=123#wechat_redirect'
    // },
    // {
    //     "name": '测试2',
    //     "type": "view",
    //     "url": 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + wechatconfig.wechatauth.appid + '&redirect_uri=' + encodeURIComponent("http://mxthink2.cross.echosite.cn/") + '&response_type=code&scope=snsapi_base&state=123#wechat_redirect'
    // }
  ],
};

router.get("/delmenu/", async (ctx, next) => {
  try {
    let delmenu = await api.removeMenu();
    console.log("菜单删除成功");
    ctx.body = "菜单删除成功";
  } catch (err) {
    console.log(err);
    ctx.body = "菜单删除失败";
  }
});

router.get("/creatmenu/", async (ctx, next) => {
  try {
    let createmenu = await api.createMenu(mymenu3);
    console.log("菜单创建成功");
    ctx.body = "菜单创建成功";
  } catch (err) {
    console.log(err);
    ctx.body = "菜单创建失败";
  }
});

var errhtml =
  '<title>抱歉，出错了</title><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=0"><link rel="stylesheet" type="text/css" href="https://res.wx.qq.com/open/libs/weui/0.4.1/weui.css">';
errhtml +=
  '<div class="weui_msg"><div class="weui_icon_area"><i class="weui_icon_info weui_icon_msg"></i></div><div class="weui_text_area"><h4 class="weui_msg_title">请在微信客户端打开链接</h4></div></div>';

//拦截所有请求，如果有token则将用户信息注入到请求中
/*
router.use(async (ctx, next) => {
    console.log('拦截的访问:' + ctx.request.href)
    //测试时跳过token验证
    console.log('拦截的访问(测试跳过):' + ctx.request.href)
    await next();
    return;
    //测试时跳过token验证结束
    let token = ctx.header.authorization;
    console.log(token)
    //var token = posttoken || ctx.query.token;


    if (ctx.header.authorization) {
        try {
            //验证token合法性
            let token = await jwt.verify(ctx.header.authorization, sitecfg.tokenKey);
            ctx.request.token = token;
        } catch (err) {
            ctx.body = { error: true, message: "验证token时出错：[" + err + "]程序终止!" };
            return;
        }
    }
    await next();
})
*/

router.post("/valitoken/", async (ctx, next) => {
  ctx.body = { vali: true, isbinder: ctx.request.token.isbinder };
  return;
});
//特殊新生报名序号 wxopenid 20210602桂岭小学时作废
router.get("/binder2/", async (ctx, next) => {
  // if (!ctx.query.code && !ctx.session.wxuserinfo) {
  //     ctx.body = errhtml
  //     return;
  // }
  //使用token认证，以上代码改为以下代码：
  if (!ctx.query.code) {
    //如果没有获得code表示来源客户端不是微信
    ctx.body = errhtml;
    return;
  }

  if (ctx.request.token) {
    //如果已经访问者已经获得token
    ctx.redirect(sitecfg.clientURL + "/?token=" + ctx.request.authorization);
    return;
  }
  //let code=ctx.query.code;

  //访问者没有token只有code，通过 code获得token
  let wxuserinfo = {
    code: ctx.query.code,
    openid: null,
    isbinder: false,
    error: false,
  };

  let getopenidurl =
    "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" +
    wechatconfig.wechatauth.appid +
    "&secret=" +
    wechatconfig.wechatauth.appsecret +
    "&code=" +
    wxuserinfo.code +
    "&grant_type=authorization_code";

  try {
    let result = await axios.get(getopenidurl);
    if (result.data.errcode) {
      ctx.body = result.data.errmsg;
      return;
    } else {
      wxuserinfo.openid = result.data.openid;
    }
  } catch (err) {
    //获取用户授权出错了，跳转到出错页面
    console.log("获取用户授权出错:" + err);
    wxuserinfo.error = true;
    ctx.body = err;
    return;
  }

  //wxuserinfo.openid="sadfsadfadf"
  try {
    if (!wxuserinfo.isbinder) {
      let finduser = await nss.findbyquery({ wxopenid: wxuserinfo.openid });
      // if (finduser.length == 1) {
      //     wxuserinfo.isbinder = true;
      //     let token = jwt.sign(wxuserinfo, sitecfg.tokenKey, { expiresIn: "1h" });
      //     ctx.redirect(sitecfg.clientURL + "/?token=" + token + "&isbinder=" + wxuserinfo.isbinder)
      //     return;
      // } else {
      //     ctx.redirect(sitecfg.clientURL+'/?openid='+wxuserinfo.openid)
      //     return;
      // }
      if (finduser.length == 1) wxuserinfo.isbinder = true;
      let token = jwt.sign(wxuserinfo, sitecfg.tokenKey, { expiresIn: "1h" });
      ctx.redirect(sitecfg.clientURL + "?token=" + token);
      //ctx.redirect("http://mxthink.cross.echosite.cn/vwechatenter2020/" + "?token=" + token)
      // ctx.redirect(sitecfg.serverURL + "/?token=" + token)
    }
  } catch (err) {
    //根据openid 查询数据库时出错，这里后期要放置出错界面
    wxuserinfo.error = true;
    console.log(err);
    ctx.body = err;
    return;
  }
});
//正常在校生查询 wxopenid
router.get("/binder/", async (ctx, next) => {
  //因报名序号不同目录而做的更改
  //let url2 = "http://mxthink.cross.echosite.cn/wechat/binder/";
  // if (!ctx.query.code && !ctx.session.wxuserinfo) {
  //     ctx.body = errhtml
  //     return;
  // }
  //使用token认证，以上代码改为以下代码：
  if (!ctx.query.code) {
    //如果没有获得code表示来源客户端不是微信
    ctx.body = errhtml;
    return;
  }

  if (ctx.request.token) {
    //如果已经访问者已经获得token
    ctx.redirect(sitecfg.clientURL + "/?token=" + ctx.request.authorization);
    // ctx.redirect(url2 + "/?token=" + ctx.request.authorization)
    return;
  }
  //let code=ctx.query.code;

  //访问者没有token只有code，通过 code获得token
  let wxuserinfo = {
    code: ctx.query.code,
    openid: null,
    isbinder: false,
    error: false,
  };

  let getopenidurl =
    "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" +
    wechatconfig.wechatauth.appid +
    "&secret=" +
    wechatconfig.wechatauth.appsecret +
    "&code=" +
    wxuserinfo.code +
    "&grant_type=authorization_code";

  try {
    let result = await axios.get(getopenidurl);
    if (result.data.errcode) {
      ctx.body = result.data.errmsg;
      return;
    } else {
      wxuserinfo.openid = result.data.openid;
    }
  } catch (err) {
    //获取用户授权出错了，跳转到出错页面
    console.log("获取用户授权出错:" + err);
    wxuserinfo.error = true;
    ctx.body = err;
    return;
  }

  //wxuserinfo.openid="sadfsadfadf"
  try {
    if (!wxuserinfo.isbinder) {
      // let finduser = await base.myFindByQuery({ 'wxopenid': wxuserinfo.openid })
      let finduser = await base.myAggregate([
        {
          $match: {
            wxopenid: wxuserinfo.openid,
          },
        },
        {
          $lookup: {
            from: "baseExtendInfo",
            localField: "_id",
            foreignField: "baseid",
            as: "baseExtendInfo",
          },
        },
        {
          $unwind: {
            path: "$baseExtendInfo",
            preserveNullAndEmptyArrays: true,
          },
        },
        {
          $project: {
            _id: 1,
            username: 1,
            gender: 1,
            wxopenid: 1,
            role: 1,
            accountType: 1,
            "baseExtendInfo.班级": 1,
          },
        },
      ]);
      // if (finduser.length == 1) {
      //     wxuserinfo.isbinder = true;
      //     let token = jwt.sign(wxuserinfo, sitecfg.tokenKey, { expiresIn: "1h" });
      //     ctx.redirect(sitecfg.clientURL + "/?token=" + token + "&isbinder=" + wxuserinfo.isbinder)
      //     return;
      // } else {
      //     ctx.redirect(sitecfg.clientURL+'/?openid='+wxuserinfo.openid)
      //     return;
      // }
      if (finduser.length == 1) wxuserinfo.isbinder = true;
      let token = jwt.sign(wxuserinfo, sitecfg.tokenKey, { expiresIn: "1h" });
      // console.log(sitecfg.clientURL+"/?token="+token)
      ctx.redirect(sitecfg.clientURL + "/?token=" + token);
      // ctx.redirect(url2 + "?token=" + token)
    }
  } catch (err) {
    //根据openid 查询数据库时出错，这里后期要放置出错界面
    wxuserinfo.error = true;
    console.log(err);
    ctx.body = err;
    return;
  }
});

//微信JSSDK调用配置
router.post("/jsconfig/", async (ctx, ncext) => {
  let cfgdata = ctx.request.body.cfgdata;
  if (cfgdata.debug == 0) {
    cfgdata.debug = false;
  } else {
    cfgdata.debug = true;
  }
  try {
    let res = await api.getJsConfig(cfgdata);
    ctx.body = { jsconfig: res };
  } catch (err) {
    //console.log(result);
    throw new Error("JSSDK授权失败:[" + err + "]");
  }
});

//获取base表的account信息
//20220213修改为统一获取用户基本信息的接口在 /sys/account/getbaseinfo
// router.get("/getbaseinfo/", async (ctx, next) => {
//   let wxuserinfo = ctx.request.token;
//   try {
//     ctx.body = { error: false, result: wxuserinfo };
//   } catch (err) {
//     ctx.body = { error: true, message: "获取base数据时出错！" };
//   }
// });

//绑定微信用户帐号(在校生)
router.post("/binder", async (ctx, next) => {
  //因报名序号不同目录而做的更改
  // sitecfg.clientURL = "http://mxthink.cross.echosite.cn/wechat/binder/";
  // if (!ctx.request.token) {
  //     ctx.body = { error: true, message: '数据链接失效或者是非法的！' }
  //     return;
  // }
  let stuinfo = ctx.request.body.stuinfo;
  let wxuserinfo = {};
  // if (!ctx.header.authorization) {
  // if (!ctx.request.token)
  //     throw new Error('关键数据链接失效或者是非法的！')
  wxuserinfo = ctx.request.token;
  // try {
  //     // wxuserinfo = await jwt.verify(ctx.header.authorization, sitecfg.tokenKey);
  //     wxuserinfo = ctx.request.token;
  // } catch (err) {
  //     throw new Error('关键数据链接失效或者是非法的！')
  //     // ctx.body = { error: true, message: '数据链接失效或者是非法的！' }
  //     // return;
  // }
  if (!stuinfo) return;
  try {
    // let user = await base.myFindOne({
    //     'username': stuinfo.stuname,
    //     'password': Enpassword(stuinfo.stupassword)
    // })
    let user = await base.myAggregate([
      {
        $match: {
          username: stuinfo.stuname,
          password: Enpassword(stuinfo.stupassword),
        },
      },
      {
        $lookup: {
          from: "baseExtendInfo",
          localField: "_id",
          foreignField: "baseid",
          as: "baseExtendInfo",
        },
      },
      {
        $unwind: "$baseExtendInfo",
      },
    ]);
    user = user[0];
    if (user) {
      if (user.wxopenid) {
        //需要改进为申请重新绑定
        ctx.body = {
          error: true,
          message: "该微信用户已经绑定！无需重复绑定！",
        };
        return;
      }
      //存openid
      let res = await base.myUpdateOne(
        { _id: user._id },
        { $set: { wxopenid: wxuserinfo.openid } }
      );
      wxuserinfo.isbinder = true;
      wxuserinfo.accountname = user.username;
      wxuserinfo.classno = user.classno;
      wxuserinfo.userid = user.baseExtendInfo.baseid;
      wxuserinfo.sid = user.baseExtendInfo.学籍号;
      wxuserinfo.role = user.role;
      wxuserinfo.accountType = user.accountType;
      try {
        delete wxuserinfo.exp;
        delete wxuserinfo.iat;
        let newtoken = await jwt.sign(wxuserinfo, sitecfg.tokenKey, {
          expiresIn: "1h",
        });
        ctx.body = { error: false, token: newtoken, isbinder: true };
        return;
      } catch (err) {
        ctx.body = { error: true, message: "重新授权过程中出错!" };
        return;
      }
    } else {
      //返回无该用户的提示
      ctx.body = {
        error: true,
        message: "该学生不存在，请检查姓名及密码输入是否正确！",
      };
    }
  } catch (err) {
    throw new Error("执行绑定时出错：" + err);
  }
});

//实验小新生获取报名号绑定20230623
router.post("/syxfaceno/", async (ctx, next) => {
  let stuinfo = ctx.request.body.stuinfo;
  let wxuserinfo = {};
  // if (!ctx.request.token) throw new Error("关键数据链接失效或者是非法的！");
  // wxuserinfo = ctx.request.token;
  if (!stuinfo) return;
  try {
    let user = await nss.findbyquery({
      stuname: stuinfo.stuname,
      sid: stuinfo.stupassword,
    });
    if (user.length != 0) {
      try {
        // let newtoken = await jwt.sign(stuinfo, sitecfg.tokenKey, {
          // expiresIn: "1h",
        // });
        //记录家长已获取
        user[0].know=true
        let temp=await nss.Save(user[0])
        ctx.body = { error: false, result:user[0] };
        return;
      } catch (err) {
        ctx.body = { error: true, message: "重新授权过程中出错!" };
        return;
      }
    } else {
      //返回无该用户的提示
      ctx.body = {
        error: true,
        message: "该学生不存在，请检查姓名及报名序号是否正确！",
      };
    }
  } catch (err) {
    throw new Error("执行绑定时出错：" + err);
  }
});


//绑定微信用户帐号(新生获取报名号绑定)
router.post("/binder2/", async (ctx, next) => {
  let stuinfo = ctx.request.body.stuinfo;
  let wxuserinfo = {};
  if (!ctx.request.token) throw new Error("关键数据链接失效或者是非法的！");
  wxuserinfo = ctx.request.token;
  if (!stuinfo) return;
  try {
    let user = await nss.findbyquery({
      stuname: stuinfo.stuname,
      sid: stuinfo.stupassword,
    });
    if (user.length != 0) {
      if (user.wxopenid) {
        //需要改进为申请重新绑定
        ctx.body = {
          error: true,
          message: "该微信用户已经绑定！无需重复绑定！",
        };
        return;
      }
      //存openid
      let res = await nss.update(stuinfo.stupassword, {
        wxopenid: wxuserinfo.openid,
      });
      wxuserinfo.isbinder = true;
      try {
        delete wxuserinfo.exp;
        delete wxuserinfo.iat;
        let newtoken = await jwt.sign(wxuserinfo, sitecfg.tokenKey, {
          expiresIn: "1h",
        });
        ctx.body = { error: false, token: newtoken, isbinder: true };
        return;
      } catch (err) {
        ctx.body = { error: true, message: "重新授权过程中出错!" };
        return;
      }
    } else {
      //返回无该用户的提示
      ctx.body = {
        error: true,
        message: "该学生不存在，请检查姓名及报名序号是否正确！",
      };
    }
  } catch (err) {
    throw new Error("执行绑定时出错：" + err);
  }
});

//绑定教师用户帐号(新生获取报名号绑定)
router.post("/binder3/", async (ctx, next) => {
  //需要openid，需要用户名和密码
  let stuinfo = ctx.request.body.stuinfo;
  let openid = ctx.request.body.openid;
  let wxuserinfo = {};
  // if (!ctx.request.token)
  //     throw new Error('关键数据链接失效或者是非法的！')
  // wxuserinfo = ctx.request.token;
  if (!stuinfo) return;
  try {
    let user = await base.myFindOne({
      username: stuinfo.stuname,
      password: Enpassword(stuinfo.stupassword),
    });
    if (user) {
      if (user.wxopenid) {
        //需要改进为申请重新绑定
        ctx.body = {
          error: true,
          message: "该微信用户已经绑定！无需重复绑定！",
        };
        return;
      }
      //存openid
      let res = await base.myUpdateOne({ _id: user._id }, { wxopenid: openid });
      wxuserinfo.isbinder = true;
      try {
        // delete wxuserinfo.exp;
        // delete wxuserinfo.iat;
        wxuserinfo.openid = openid;
        wxuserinfo.role = user.role;
        wxuserinfo.accountType = user.accountType;
        wxuserinfo.accountname = user.username;
        wxuserinfo.classno = user.classno;
        wxuserinfo.grade = user.grade;
        wxuserinfo.userid = user._id;
        wxuserinfo.gender = user.gender;
        let newtoken = await jwt.sign(wxuserinfo, sitecfg.tokenKey, {
          expiresIn: "1h",
        });
        ctx.body = { error: false, token: newtoken, isbinder: true };
        return;
      } catch (err) {
        ctx.body = { error: true, message: "重新授权过程中出错!" };
        return;
      }
    } else {
      //返回无该用户的提示
      ctx.body = {
        error: true,
        message: "该教师不存在，请检查姓名及密码是否正确！",
      };
    }
  } catch (err) {
    throw new Error("执行绑定时出错：" + err);
  }
});

//密码HASH
function Enpassword(password) {
  var sha1 = crypto.createHash("sha1");
  sha1.update(password);
  let r=sha1.digest("hex");
  console.log(r)
  return r;
}

module.exports = router;
